#include<memory>

#include "TcpServer.hpp"


using namespace wyl;


//业务处理
static Response calculator(const Request &req)
{
    Response resp(0, 0);
    switch (req.op_)
    {
    case '+':
        resp.result_ = req.x_ + req.y_;
        break;
    case '-':
        resp.result_ = req.x_ - req.y_;
        break;
    case '*':
        resp.result_ = req.x_ * req.y_;
        break;
    case '/':
        if (0 == req.y_)
            resp.code_ = 1;
        else
            resp.result_ = req.x_ / req.y_;
        break;
    case '%':
        if (0 == req.y_)
            resp.code_ = 2;
        else
            resp.result_ = req.x_ % req.y_;
        break;
    default:
        resp.code_ = 3;
        break;
    }
    return resp;
}


void HandlerRequest(Connection* conn , std::string request)
{
    //反序列化字符串
    DLOG("HandlerRequers already been called , request : %s\n",request.c_str());
    Request req;
    req.Deserialized(request);

    //2.处理业务
    Response resp = calculator(req); 
    
    //3.序列化构建应答
    std::string sender = resp.Serialize(); 
    sender = Encode(sender);//加上分隔符

    //4.把信息提交给连接的输出缓冲区
    conn->_outbuff += sender; //加入进输出缓冲区
    //开启服务器的关心写入事件
    conn->_tsvr->EnableReadWrite(conn,true,true);
}

int main()  
{
    std::unique_ptr<TcpServer> svr(new TcpServer());
    svr->Start(HandlerRequest);
    return 0 ;
}